package homework021.controller;

import homework021.domain.Goods;
import homework021.service.GoodsServiceImpl;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 商品控制器
 *
 * @author itheima
 */
public class GoodsController {
    private GoodsServiceImpl service = new GoodsServiceImpl();

    /**
     * 添加商品
     *
     * @param goodsId 商品编号
     * @param name    商品名
     * @param price   价格
     * @param weight  重量
     */
    public void addGoods(String goodsId, String name, String price, String weight) throws IOException {
        // 检查商品是否已存在
        boolean exists = service.idIsExists(goodsId);
        if (exists) {
            System.out.println("商品已存在");
            return;
        }

        // 构建数据
        Goods goods = new Goods(goodsId, name, price, weight);

        // 添加数据
        boolean result = service.add(goods);

        System.out.println(result ? "商品添加成功！" : "商品添加失败！");
    }

    /**
     * 删除商品
     *
     * @param goodsId 商品编号
     */
    public void deleteGoodsById(String goodsId) throws IOException {

        boolean result = service.deleteById(goodsId);

        System.out.println(result ? "商品删除成功！" : "商品删除失败！");
    }

    /**
     * 修改商品
     */
    public void updateGoods(String goodsId, String name, String price) throws IOException {
        // 根据id查询商品数据
        Goods goods = service.findById(goodsId);
        // 修改内容
        goods.setPrice(price);
        goods.setName(name);

        // 写入新内容
        boolean result = service.update(goodsId, goods);

        System.out.println(result ? "商品修改成功！" : "商品修改失败！");
    }

    /**
     * 查看所有商品
     */
    public void findAllGoods() throws IOException {
        List<Goods> goodsList = service.findAll();
        if (Objects.isNull(goodsList)) {
            System.out.println("商品为空");
        }

        for (Goods goods : goodsList) {
            System.out.println(goods);
        }
    }
}
